<template>
  <v-container>
    <v-row>
      <h1 class="font-weight-light">
        {{card.cardNo}}
        <v-chip
          class="ma-2"
          color="primary"
          v-if="card.cardNo"
        >
          {{card.status === 1 ? 'Active' : 'Suspended'}}
        </v-chip>
      </h1>
    </v-row>
    <v-row>
      <v-col sm="12" md="8">
        <v-form v-model="valid">
          <v-card>
            <v-card-title>Account</v-card-title>
            <v-card-text v-if="card.cardNo">
              <v-text-field
                label="Card Number" name="cardNo"
                prepend-icon="mdi-account"
                type="text" disabled
                autocomplete="off"
                v-model="cardInfo.cardNo"
              ></v-text-field>
              <v-text-field
                label="Password (Leave empty if unchanged)"
                name="password"
                prepend-icon="mdi-lock"
                type="password"
                :rules="passwordRules"
                v-model="cardInfo.password"
              ></v-text-field>
            </v-card-text>
            <v-card-actions>
              <v-spacer/>
              <v-btn
                text
                @click="handleSave"
                :loading="loading"
                :disabled="!valid"
              >Save</v-btn>
            </v-card-actions>
          </v-card>
        </v-form>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
  import {updateCard} from "../../../api/card";

  export default {
    name: 'profile',
    data: () => ({
      cardInfo: {
        cardNo: null,
        password: null,
        status: null,
      },
      loading: false,
      valid: false,
      passwordRules: [
        v => !!v || 'Required',
        v => !!v && /^\d{6}$/.test(v) || 'Must be 6 numbers long'
      ]
    }),
    computed: {
      card() {
        return this.$store.getters.card;
      }
    },
    methods: {
      handleSave() {
        this.loading = true;
        updateCard(this.cardInfo).subscribe(res => {
          if (res.data) {
            this.$toasted.info('Card Profile updated');
          }
          else {
            this.$toasted.error('No response');
          }
          this.loading = false;
        }, err => {
          this.loading = false;
          this.$toasted.error(err);
        })
      }
    },
    mounted() {
      this.$store.dispatch('card/resume').then(res => {
        this.cardInfo.cardNo = res.cardNo;
        this.cardInfo.status = res.status;
      })
    }
  };
</script>
